import {
  Baidu_App_Id,
  Baidu_App_Key
} from './config'
import md5 from './md5.min'

export const translate = ({
  from = 'auto',
  to,
  q
}) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中...',
    })
    const time = new Date().getTime()
    wx.request({
      url: 'https://fanyi-api.baidu.com/api/trans/vip/translate',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        q,
        from,
        to,
        appid: Baidu_App_Id,
        salt: time,
        sign: md5(`${Baidu_App_Id}${q}${time}${Baidu_App_Key}`)
      },
      success: ({
        statusCode,
        errMsg,
        data
      }) => {
        if (statusCode === 200) {
          resolve(data)
        } else {
          reject(errMsg)
        }
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  })
}